package com.acwing.partition3;

import java.io.*;
import java.util.Random;

/**
 * @author `RKC`
 * @date 2022/5/3 9:17
 */
public class AC265营业额统计 {

    private static final int N = 33010, INF = 0x3f3f3f3f;
    private static final Random r = new Random();
    private static Node[] tr = new Node[N];
    private static int n, root, idx = 0;

    private static StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    private static PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        n = nextInt();
        build();
        long ans = 0;
        for (int i = 0; i < n; i++) {
            int x = nextInt();
            if (i == 0) ans += x;
            else ans += Math.min(x - getPrev(root, x), getNext(root, x) - x);
            root = insert(root, x);
        }
        writer.println(ans);
        writer.flush();
    }

    private static int getPrev(int p, int key) {
        if (p == 0) return -INF;
        if (key < tr[p].key) return getPrev(tr[p].l, key);
        return Math.max(tr[p].key, getPrev(tr[p].r, key));
    }

    private static int getNext(int p, int key) {
        if (p == 0) return INF;
        if (key > tr[p].key) return getNext(tr[p].r, key);
        return Math.min(tr[p].key, getNext(tr[p].l, key));
    }

    private static int insert(int p, int key) {
        if (p == 0) return create(key);
        if (key < tr[p].key) {
            tr[p].l = insert(tr[p].l, key);
            if (tr[p].rnd < tr[tr[p].l].rnd) p = zig(p);
        } else if (key > tr[p].key) {
            tr[p].r = insert(tr[p].r, key);
            if (tr[p].rnd < tr[tr[p].r].rnd) p = zag(p);
        }
        return p;
    }

    private static void build() {
        tr[0] = new Node(0);
        root = create(-INF);
        tr[root].r = create(INF);
        if (tr[2].rnd > tr[1].rnd) root = zag(root);
    }

    private static int zig(int p) {
        int q = tr[p].l;
        tr[p].l = tr[q].r;
        tr[q].r = p;
        return q;
    }

    private static int zag(int p) {
        int q = tr[p].r;
        tr[p].r = tr[q].l;
        tr[q].l = p;
        return q;
    }

    private static int create(int key) {
        tr[++idx] = new Node(key);
        tr[idx].rnd = r.nextInt(N);
        return idx;
    }

    private static class Node {
        private int l, r, key, rnd;

        public Node(int key) {
            this.key = key;
        }
    }

    private static int nextInt() throws IOException {
        tokenizer.nextToken();
        return (int) tokenizer.nval;
    }
}
